﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using MvcShop.Models.ViewDataModels;

namespace MvcShop.Models.Repositories
{
    public class NewsRepository:BaseRepositoryBase<News>,INewsRepository<News>
    {
        public NewsRepository()
        {
            this.EntitiesSetName = "Newses";
        }

        public void Del(IEnumerable<int> values)
        {
            var query = this.EntitySet.Where(ContainsCriteria.ContainsExpression<News, int>(c => c.NewsId, values)).ToList();
            foreach (var value in query)
            {
                this.dataContext.DeleteObject(value);
            }
            this.SaveChanges();
        }

        public IList<News> GetTitleList(ICriteria criteria, int page, int pageSize, Order orderExpr)
        {
            if (criteria == null || orderExpr == null)
                throw new ArgumentNullException("criteria");
            var query = this.EntitySet.Where(criteria.Expression, criteria.Parameters.Select(p => new ObjectParameter(p.Name, p.Value)).ToArray());

            return ToList(orderExpr.OrderFrom<News>(query).Skip((page - 1) * pageSize).Take(pageSize));
        }

        public IList<NewsList> FindAll(int page, int pageSize)
        {
            var query = (from news in this.EntitySet 
                         orderby news.NewsId descending 
                         select new NewsList{ NewsId = news.NewsId, 
                             Title = news.Title, 
                             DateTime = news.DateTime }).Skip((page - 1) * pageSize).Take(pageSize).ToList();
            return query;
        }

        public IList<NewsList> GetHeadLine(int size)
        {
            var query = (from news in this.EntitySet
                         where news.HeadLine == true
                         orderby news.DateTime descending
                         select new NewsList
                         {
                             NewsId = news.NewsId,
                             Title = news.Title,
                             HighLight = news.HighLight,
                             DateTime = news.DateTime
                         }).Take(size).ToList();

            return query;
        }
    }
}
